<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { Bell } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { useRouter } from 'vue-router'
import { getUnreadMessageCountByType } from '../api/message'

const userStore = useUserStore()
const router = useRouter()
const unreadCounts = ref<Record<string, number>>({})
const unreadMessages = defineModel<number>('unreadMessages', { required: false })
let timer: number | null = null

// 获取未读消息类型统计
const fetchUnreadCounts = async () => {
  try {
    if (!userStore.id) return
    
    const res = await getUnreadMessageCountByType(Number(userStore.id))
    if (res && res.code === 200 && res.data) {
      unreadCounts.value = res.data
      console.log('未读消息统计:', unreadCounts.value)
    }
  } catch (error) {
    console.error('获取未读消息统计失败:', error)
  }
}

// 获取友好的消息类型名称
const getMessageTypeName = (type: string): string => {
  const typeNames: Record<string, string> = {
    postLike: '帖子点赞',
    resourceLike: '资源点赞',
    comment: '评论',
    system: '系统消息'
  }
  return typeNames[type] || type
}

// 检查是否有未读消息
const hasUnreadMessages = (): boolean => {
  return Object.values(unreadCounts.value).some(count => count > 0)
}

// 鼠标移入时拉取未读统计
const handleMouseEnter = () => {
  fetchUnreadCounts()
}

// 点击跳转到消息中心
const handleClick = () => {
  router.push('/message')
}

// 组件挂载时开始定时拉取
onMounted(() => {
  fetchUnreadCounts() // 立即执行一次
  timer = setInterval(fetchUnreadCounts, 30000) // 每30秒刷新一次
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})
</script>

<template>
  <el-popover
    placement="bottom-start"
    width="320"
    trigger="hover"
    popper-class="message-popover"
    @show="handleMouseEnter"
  >
    <template #reference>
      <el-menu-item index="2" @click="handleClick" style="cursor:pointer;">
        <el-icon><Bell /></el-icon>消息
        <el-badge v-if="unreadMessages && unreadMessages > 0"
                 :value="unreadMessages"
                 class="item"
                 type="primary" />
      </el-menu-item>
    </template>
    <el-scrollbar style="max-height: 300px;">
      <!-- 只要有未读消息就显示统计 -->
      <div v-if="Object.values(unreadCounts).some(count => count > 0)" class="unread-summary purple-bg">
        <div class="unread-title purple-main">未读消息统计</div>
        <template v-for="(count, type) in unreadCounts" :key="type">
          <div v-if="count > 0" class="unread-item purple-text unread-item-bg full-width-row">
            <span>{{ getMessageTypeName(type) }}：<b>{{ count }}</b> 条</span>
          </div>
        </template>
      </div>
      <!-- 没有未读消息时显示 -->
      <div v-else style="padding: 16px; color: #888; text-align: center;">暂无未读消息</div>
    </el-scrollbar>
  </el-popover>
</template>

<style scoped>
.message-popover {
  padding: 0;
}
.message-list {
  list-style: none;
  margin: 0;
  padding: 0;
}
.message-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}
.msg-title {
  font-weight: bold;
  margin-bottom: 4px;
}
.msg-content {
  color: #666;
  font-size: 13px;
  margin-bottom: 2px;
}
.msg-time {
  color: #aaa;
  font-size: 12px;
  text-align: right;
}
.unread-summary {
  padding: 14px 20px 10px 20px;
  background: #f6f8fa;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 8px 8px 0 0;
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}
.unread-summary.purple-bg {
  padding: 14px 20px 10px 20px;
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 8px 8px 0 0;
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}
.unread-title {
  color: #222;
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 10px;
  letter-spacing: 1px;
}
.unread-title.purple-main {
  color: #7c3aed;
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 10px;
  letter-spacing: 1px;
}
.unread-item {
  margin-bottom: 6px;
  color: #409EFF;
  font-size: 14px;
  padding-left: 2px;
  transition: color 0.2s;
}
.unread-item.purple-text {
  margin-bottom: 6px;
  color: #7c3aed;
  font-size: 14px;
  padding-left: 2px;
  transition: color 0.2s;
}
.unread-item.purple-text.unread-item-bg {
  background: #f3e8ff;
  border-radius: 6px;
  padding: 6px 12px;
  margin-bottom: 8px;
  color: #7c3aed;
  font-size: 14px;
  display: inline-block;
}
.unread-item.purple-text.unread-item-bg:last-child {
  margin-bottom: 0;
}
.unread-item:last-child {
  margin-bottom: 0;
}
.unread-item.purple-text:last-child {
  margin-bottom: 0;
}
.unread-item.purple-text.unread-item-bg.full-width-row {
  background: #f3e8ff;
  border-radius: 6px;
  padding: 6px 12px;
  margin-bottom: 8px;
  color: #7c3aed;
  font-size: 14px;
  width: 100%;
  display: block;
  box-sizing: border-box;
}
.unread-item.purple-text.unread-item-bg.full-width-row:last-child {
  margin-bottom: 0;
}
</style>
